using System;
using System.Web.UI;
using System.Web.Compilation;
using System.CodeDom;
using System.Reflection;

namespace AspNetExtensions.ExpressionBuilders
{
    /// <summary>
    /// Outputs the version information for the calling assembly. Format can be Version:All or Version:MajorMinor.
    /// </summary>
    /// 
    [ExpressionPrefix("Version")]
    public class VersionExpressionBuilder : ExpressionBuilder
    {
        public override CodeExpression GetCodeExpression(
            BoundPropertyEntry entry, object parsedData,
            ExpressionBuilderContext context)
        {
            string param = entry.Expression;
            AssemblyName assembly = Assembly.GetCallingAssembly().GetName();
            if (String.Compare(param, "All", true) == 0)
                return new CodePrimitiveExpression
                    (String.Format("{0}.{1}.{2}.{3}",
                    assembly.Version.Major,
                    assembly.Version.Minor,
                    assembly.Version.Build,
                    assembly.Version.Revision));
            else if (String.Compare(param, "MajorMinor", true) == 0)
                return new CodePrimitiveExpression
                    (String.Format("{0}.{1}",
                     assembly.Version.Major,
                     assembly.Version.Minor));
            else
                throw new InvalidOperationException
                    ("Use $ Version:All or $ Version:MajorMinor");
        }
    }
}

